package com.mishow.adapter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.text.TextUtils.TruncateAt;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mishow.R;
import com.mishow.activity.StarDetailsActivity;
import com.mishow.adapter.StarResultFragmentAdapter.MyViewHolder;
import com.mishow.bean.ChatVO;
import com.mishow.bean.CommentVO;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.utils.TimeUtil;
import com.mishow.utils.ImageLoader.ImageLoaderProxy;
import com.mishow.widget.AdjustLayout;
import com.mishow.widget.MyListView;
import com.mishow.widget.RoundCornerImageView;
import com.mishow.widget.nine.CustomImageView;
import com.mishow.widget.nine.Image;
import com.mishow.widget.nine.NineGridlayout;
import com.mishow.widget.nine.ScreenTools;

/**
 * 
 * 作者：wei.miao<br/>
 * 描述：星秀列表Adapter
 */
@SuppressLint("SimpleDateFormat")
public class StarResultFragmentAdapter extends
		RecyclerView.Adapter<MyViewHolder> {

	private ArrayList<ChatVO> mChats;
	/** 图片列表 **/
	private ArrayList<Image> mDatalist;
	/** 评论列表 **/
	private ArrayList<CommentVO> mCommentVOs;

	private Context mContext;

	private OnClickInterface mOnClickInterface;

	private SharedPreferencesUtil preferencesUtil;

	public void setOnClickInterface(OnClickInterface onClickInterface) {

		this.mOnClickInterface = onClickInterface;
	}

	public StarResultFragmentAdapter(Context mContext, ArrayList<ChatVO> chats) {

		this.mContext = mContext;
		this.mChats = chats;
		mCommentVOs = new ArrayList<>();
		preferencesUtil = new SharedPreferencesUtil(mContext);

	}

	private void setImage(ArrayList<String> images) {
		mDatalist = new ArrayList<>();
		mDatalist.clear();
		for (int i = 0; i < images.size(); i++) {
			// 等比缩小 50%：压缩图片质量30
			Image image = new Image(images.get(i)
					+ "?imageMogr2/thumbnail/!50p/quality/20", 117, 117);
			mDatalist.add(image);
		}
	}

	// 填充onCreateViewHolder方法返回的holder中的控件
	@Override
	public void onBindViewHolder(final MyViewHolder holder, final int position) {

		final ChatVO chatVO = mChats.get(position);

		if (chatVO.getImageList() != null && chatVO.getImageList().size() > 0) {

			setImage(chatVO.getImageList());
		}

		holder.txt_star_nikename.setText(chatVO.getUserCname());
		// 是否实名
		holder.image_is_name
				.setVisibility(chatVO.getRealName() == 1 ? View.VISIBLE
						: View.GONE);
		if (chatVO.getChatCreatetime() != null && !chatVO.getChatCreatetime().equals("")) {
			
			holder.text_comment_update_time.setText(TimeUtil.update_time(chatVO.getChatCreatetime()));
		}
		
		if (chatVO.getUserProfession() != null
				&& !chatVO.getUserProfession().equals("")) {
			holder.adjust_plane_layout.setVisibility(View.VISIBLE);
			if (chatVO.getUserProfession().contains(",")) {
				String[] tempPro = chatVO.getUserProfession().split(",");
				holder.adjust_plane_layout.removeAllViews();
				for (int i = 0; i < tempPro.length; i++) {
					View view_plane = LayoutInflater.from(mContext).inflate(R.layout.item_comment_pro, null);
					CheckBox textView = (CheckBox) view_plane
							.findViewById(R.id.hot_search_text);
					textView.setText(tempPro[i]);
					textView.setSingleLine(true);
					textView.setEllipsize(TruncateAt.MIDDLE);
					holder.adjust_plane_layout.addView(view_plane);
				}
			} else {
				holder.adjust_plane_layout.removeAllViews();
				View view_plane = LayoutInflater.from(mContext).inflate(R.layout.item_hot_search, null);
				CheckBox textView = (CheckBox) view_plane
						.findViewById(R.id.hot_search_text);
				textView.setText(chatVO.getUserProfession());
				textView.setSingleLine(true);
				textView.setEllipsize(TruncateAt.MIDDLE);
				textView.setBackgroundResource(R.drawable.shape_selectitem_press);
				holder.adjust_plane_layout.addView(view_plane);
			}
		} else {

			holder.adjust_plane_layout.setVisibility(View.GONE);
		}

		// 评论列表
		ArrayList<CommentVO> commentList = (ArrayList<CommentVO>) chatVO.getComments();
		if (commentList != null && commentList.size() > 0) {
			mCommentVOs.clear();
			holder.relative_comment_content.setVisibility(View.VISIBLE);
			if (chatVO.getCommentNum() > 3) {
				holder.text_look_comment.setText("查看全部"
						+ chatVO.getCommentNum() + "条评论");
				holder.text_look_comment.setVisibility(View.VISIBLE);
			} else {
				holder.text_look_comment.setVisibility(View.GONE);
			}
			mCommentVOs.addAll(commentList);
			StarCommnetAdapter mCommnetAdapter = new StarCommnetAdapter(mContext, mCommentVOs);
			holder.listview_starshows.setAdapter(mCommnetAdapter);
			
			mCommnetAdapter.setOnCommentInfoClick(new OnCommnetInfoClick() {

				@Override
				public void setEditText(String commentRespondentCname) {

					holder.edit_comment.requestFocus();
					holder.edit_comment.setHint("回复" + commentRespondentCname);
					InputMethodManager imm = (InputMethodManager) mContext
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.showSoftInput(holder.edit_comment,
							InputMethodManager.SHOW_IMPLICIT);
				}
			});
		} else {
			holder.relative_comment_content.setVisibility(View.GONE);
		}
		holder.txt_star_desc.setText(chatVO.getChatText());

		holder.text_star_location.setSingleLine(true);
		holder.text_star_location.setEllipsize(TruncateAt.END);
		holder.text_star_location.setText(chatVO.getChatPosition());
		holder.text_like_number.setText(chatVO.getLikedNum() + "");
		// 九宫格
		if (mDatalist.isEmpty()) {
			holder.iv_oneimage.setVisibility(View.GONE);
			holder.include_nine.setVisibility(View.GONE);

		} else {
			if (mDatalist != null && mDatalist.size() > 0) {

				if (mDatalist.size() == 1) {
					holder.include_nine.setVisibility(View.VISIBLE);
					holder.iv_oneimage.setVisibility(View.VISIBLE);
					handlerOneImage(holder, mDatalist.get(0));
				} else {
					holder.include_nine.setVisibility(View.VISIBLE);
					holder.iv_oneimage.setVisibility(View.VISIBLE);
					holder.iv_ngrid_layout.setImagesData(mDatalist);
				}
			}
		}

		String likedHead = mChats.get(position).getLikedHead();
		if (likedHead != null && !likedHead.equals("")) {

			ImageLoaderProxy.getInstance(mContext).displayImage(likedHead,
					holder.image_head_one, R.drawable.icon_star_detail_sm);
		}
		// 评论点击事件start
		holder.text_content.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// 判断当前登录userId是否用发布动态的userId相同
				// 如果相同表示是主题评论.否则为回复
				int type;
				if (preferencesUtil.getUserId().equals(chatVO.getUserId())) {
					type = 1;
				} else {
					type = 0;
				}
				mOnClickInterface.onClickComment(holder.edit_comment.getText()
						.toString().trim(), chatVO.getUserId() + "",
						chatVO.getId() + "", "", type + "");
			}
		});

		if (preferencesUtil.getUserId().equals(chatVO.getUserId())) {
			holder.btn_comment_focus.setVisibility(View.GONE);
		} else {
			holder.btn_comment_focus.setVisibility(View.VISIBLE);
			holder.btn_comment_focus.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mOnClickInterface.onClickFocus(chatVO.getUserId() + "");
				}
			});
		}

		holder.text_look_comment.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				StarDetailsActivity.intoActivity(mContext, chatVO.getId() + "");
			}
		});
		holder.img_like_share.setOnClickListener(onClickListener);
		holder.image_like.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mOnClickInterface.onClickLike(chatVO.getId() + "");
			}
		});
		
		if( mOnItemClickListener!= null){ 
			// ListView套用EditText解决EditText无法点击问题start(不需要在根布局添加android:descendantFocusability="blocksDescendants")
			holder.getView().setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mOnItemClickListener.onClick(position);  
				}
			});
			// ListView套用EditText解决EditText无法点击问题end
		}

	}

	// 重写onCreateViewHolder方法，返回一个自定义的ViewHolder
	// 创建新View，被LayoutManager所调用
	@Override
	public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int arg1) {

		MyViewHolder holder = new MyViewHolder(LayoutInflater.from(mContext)
				.inflate(R.layout.fragment_star_item, viewGroup, false));

		return holder;
	}

	public class MyViewHolder extends ViewHolder {

		private View mView;
		
		public View getView(){
			return mView;
		}
		public MyViewHolder(View view) {
			super(view);
			this.mView = view;
			img_round_icon = (RoundCornerImageView) view
					.findViewById(R.id.img_round_icon);
			txt_star_nikename = (TextView) view
					.findViewById(R.id.txt_star_nikename);
			image_is_name = (ImageView) view.findViewById(R.id.image_is_name);
			adjust_plane_layout = (AdjustLayout) view
					.findViewById(R.id.adjust_plane_layout);

			txt_star_desc = (TextView) view.findViewById(R.id.txt_star_desc);
			text_star_location = (TextView) view
					.findViewById(R.id.text_star_location);
			text_comment_update_time = (TextView) view
					.findViewById(R.id.text_comment_update_time);

			image_head_one = (RoundCornerImageView) view
					.findViewById(R.id.image_head_one);
			image_head_two = (RoundCornerImageView) view
					.findViewById(R.id.image_head_two);
			image_head_three = (RoundCornerImageView) view
					.findViewById(R.id.image_head_three);
			image_head_four = (RoundCornerImageView) view
					.findViewById(R.id.image_head_four);
			image_head_five = (RoundCornerImageView) view
					.findViewById(R.id.image_head_five);
			image_head_six = (RoundCornerImageView) view
					.findViewById(R.id.image_head_six);

			text_like_number = (TextView) view
					.findViewById(R.id.text_like_number);

			listview_starshows = (MyListView) view
					.findViewById(R.id.listview_starshows);
			text_look_comment = (TextView) view
					.findViewById(R.id.text_look_comment);
			relative_comment_content = (RelativeLayout) view
					.findViewById(R.id.relative_comment_content);

			edit_comment = (EditText) view.findViewById(R.id.edit_comment);
			// 九宫格start
			include_nine = view.findViewById(R.id.include_nine);
			iv_oneimage = (CustomImageView) view.findViewById(R.id.iv_oneimage);
			iv_ngrid_layout = (NineGridlayout) view.findViewById(R.id.iv_ngrid_layout);
			// 九宫格end

			btn_comment_focus = (Button) view
					.findViewById(R.id.btn_comment_focus);
			image_like = (ImageView) view.findViewById(R.id.image_like);
			img_like_share = (ImageView) view.findViewById(R.id.img_like_share);
			text_content = (TextView) view.findViewById(R.id.text_content);
			
		}

		/** 发布人头像 **/
		RoundCornerImageView img_round_icon;

		/** 昵称 **/
		TextView txt_star_nikename;
		/** 是否实名 **/
		ImageView image_is_name;
		/** 职业类型 **/
		AdjustLayout adjust_plane_layout;
		/** 关注点击 **/
		Button btn_comment_focus;
		/** 描述 **/
		TextView txt_star_desc;
		/** 位置 **/
		TextView text_star_location;
		/** 评论更新时间 **/
		TextView text_comment_update_time;

		/** 点赞点击 **/
		ImageView image_like;

		/** 评论头像 1 **/
		RoundCornerImageView image_head_one;
		/** 评论头像 2 **/
		RoundCornerImageView image_head_two;
		/** 评论头像 3 **/
		RoundCornerImageView image_head_three;
		/** 评论头像 4 **/
		RoundCornerImageView image_head_four;
		/** 评论头像 5 **/
		RoundCornerImageView image_head_five;
		/** 评论头像 6 **/
		RoundCornerImageView image_head_six;

		/** 点赞数量 **/
		TextView text_like_number;

		/** 分享转发点击 **/
		ImageView img_like_share;

		RelativeLayout relative_comment_content;
		/** 评论列表 **/
		MyListView listview_starshows;
		/** 查看全部评论 **/
		TextView text_look_comment;

		/** 输入评论 **/
		EditText edit_comment;

		/** 评论点击 **/
		TextView text_content;

		/** 九宫格 **/
		NineGridlayout iv_ngrid_layout;
		/** 九宫格布局 **/
		View include_nine;
		/** 九宫格只有一张图片时显示使用 **/
		CustomImageView iv_oneimage;

	}

	private void handlerOneImage(MyViewHolder viewHolder, Image image) {
		int totalWidth;
		int imageWidth;
		int imageHeight;
		ScreenTools screentools = ScreenTools.instance(mContext);
		totalWidth = screentools.getScreenWidth() - screentools.dip2px(117);
		imageWidth = screentools.dip2px(image.getWidth());
		imageHeight = screentools.dip2px(image.getHeight());
		if (image.getWidth() <= image.getHeight()) {
			if (imageHeight > totalWidth) {
				imageHeight = totalWidth;
				imageWidth = (imageHeight * image.getWidth())
						/ image.getHeight();
			}
		} else {
			if (imageWidth > totalWidth) {
				imageWidth = totalWidth;
				imageHeight = (imageWidth * image.getHeight())
						/ image.getWidth();
			}
		}
		ViewGroup.LayoutParams layoutparams = viewHolder.iv_oneimage.getLayoutParams();
		layoutparams.height = imageHeight;
		layoutparams.width = imageWidth;
		viewHolder.iv_oneimage.setLayoutParams(layoutparams);
		viewHolder.iv_oneimage.setClickable(true);
		// viewHolder.iv_oneimage.setScaleType(android.widget.ImageView.ScaleType.CENTER);
		viewHolder.iv_oneimage.setImageUrl(image.getUrl());
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.img_like_share:
				mOnClickInterface.onClickLikeShare();
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 描述：点击事件监听
	 */
	public interface OnClickInterface {
		/**
		 * 评论点击
		 * 
		 * @param comment
		 *            评论内容
		 * @param commentReviewersId
		 *            评论者ID
		 * @param commentChatId
		 *            评论内容ID
		 * @param commentRespondentId
		 *            被回复者ID
		 * @param commentType
		 *            评论类型(0-主题评论,1-回复)
		 * 
		 */
		void onClickComment(String comment, String commentReviewersId,
				String commentChatId, String commentRespondentId,
				String commentType);

		/** 分享转发 **/
		void onClickLikeShare();

		/** 点赞点击 **/
		void onClickLike(String chatId);

		/**
		 * 关注点击
		 * 
		 * @param userId
		 **/
		void onClickFocus(String userId);

	}

	/**
	 * 
	 * 作者：wei.miao <br/>
	 * 描述：点击评论信息，回传给EditText
	 */
	public interface OnCommnetInfoClick {
		/**
		 * @param commentRespondentCname
		 *            被回复者昵称
		 */
		void setEditText(String commentRespondentCname);
	}

	@Override
	public int getItemCount() {
		return mChats == null ? 0 : mChats.size();
	}
	
	private OnItemClickListener mOnItemClickListener;
	
	//给RecyclerView的Item添加点击事件
	public interface OnItemClickListener{
        void onClick( int position);
        void onLongClick( int position);
     }
	public void setOnItemClickListener(OnItemClickListener onItemClickListener ){
		
        this.mOnItemClickListener = onItemClickListener;
     }

}
